package com.huobi.pro.trade;

import java.math.BigDecimal;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.alibaba.fastjson.JSONObject;
import com.huobi.db.bean.Account;
import com.huobi.pro.account.AccountService;
import com.huobi.pro.trade.client.OrderRestClient;
import com.huobi.pro.trade.rep.BuyResult;
import com.huobi.pro.trade.rep.CancelResult;
import com.huobi.pro.trade.rep.QryResult;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service
public class BuyService implements Buy {

	@Autowired OrderRestClient futurePostV1;
	@Autowired AccountService accountService;

	public QryResult order(String orderId) {
		
		final QryResult r = new QryResult();
		String result = this.futurePostV1.order(orderId);
		
		if (StringUtils.isEmpty(result)) {
			return r.error("query order error!");
		}
		JSONObject rep = JSONObject.parseObject(result);
		String status = rep.getString("status");
		JSONObject data = rep.getJSONObject("data");
		r.setStatus(status);
		if(r.isSuccess()) {
			r.setTradeAmount(data.getBigDecimal("field-amount")); // 成交数量
			r.setPlaceAmount(data.getBigDecimal("amount")); // 提交数据
			r.setTradeStatus(data.getString("state"));// 火币的订单状态
		}

		return r;
	}

	public BuyResult buy(String orderid,BigDecimal argAmount,BigDecimal argPrice) {
		BuyResult result = new BuyResult();
		String accountType = "spot";
		Account account = accountService.getAccountId(accountType);
		
		if (account !=null ) {
			String accountId= account.getAccountId();
			String symbol = "trxusdt";
			String type = "buy-limit";
			String amount = argAmount.toPlainString();//"100";
			String price = argPrice.toPlainString();//"0.050000";
			String place = futurePostV1.place(orderid.toString(), accountId, symbol, type, amount, price);
			
			if(StringUtils.isEmpty(place)) {
				return result.error("place error");
			}
			JSONObject obj = JSONObject.parseObject(place);
			log.info("下单返回：" + place);
			
			String status = obj.getString("status");
			String data = obj.getString("data");
			result.setStatus(status);
			result.setHuobiOrderId(data);
		} else {
			log.warn("account {} not exists !",accountType);
			result.error("no account");
		}
		return result;
	}

	public CancelResult cancel(String huobiOrder) {
		CancelResult cr = new CancelResult();
		String re = futurePostV1.cancelOrder(huobiOrder);

		if (StringUtils.isEmpty(re))
			return cr.error("cancel order error.");

		JSONObject obj = JSONObject.parseObject(re);
		cr.setStatus(obj.getString("status"));
		cr.setOrderState(obj.getString("order-state"));
		
		return cr;
	}

}
